package hongcaosp.app.android.comment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public abstract class LoadMoreHandler extends RecyclerView.OnScrollListener {
    private int visibleThreshold = 3;
    private boolean loadMore;
    private LinearLayoutManager linearLayoutManager;
    private boolean isLoading;

    public void setLoadMore(boolean loadMore) {
        this.loadMore = loadMore;
    }

    public LoadMoreHandler(LinearLayoutManager linearLayoutManager) {
        this.linearLayoutManager = linearLayoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        int itemCount = linearLayoutManager.getItemCount();
        int lastPosition = linearLayoutManager.findLastVisibleItemPosition();
        //如果当前不是正在加载更多，并且到了该加载更多的位置，加载更多。
        if (!isLoading && (lastPosition >= (itemCount - visibleThreshold))) {
            if (loadMore) {
                isLoading = true;
                loadMore();
            }
        }
    }

    public void loadMoreFinish(boolean canLoadMore) {
        loadMore = canLoadMore;
        isLoading = false;
    }

    public abstract void loadMore();
}
